package com.project.study.farming.common.interceptor;

import com.project.study.farming.common.constant.Constant;
import com.project.study.farming.common.entity.po.UserPo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 拦截器，验证登录信息
 * @since 2020-03-03
 */
@Component
public class FarmingInterceptor extends HandlerInterceptorAdapter {

    /**
     * 白名单
     */
    private static List<String> excludePathPatterns = Arrays.asList("/user/login", "/user/reg", "/index", "/reg.html", "error.html");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        System.out.println(String.format("请求路径：%s", uri));
        HttpSession session = request.getSession();
        UserPo user = (UserPo) session.getAttribute(Constant.CUR_USER.name());
        System.out.println(String.format("当前人信息：%s", user));
        if(Objects.isNull(user)){
            if(!checkUri(uri)){
                response.sendRedirect(String.format("%s/index", request.getContextPath()));
            }
        }
        return true;
    }

    private boolean checkUri(String uri){
        if(uri.startsWith("/images") || uri.startsWith("/static")){
            return true;
        }
        return excludePathPatterns.contains(uri);
    }
}
